package com.java.modebing.test.util;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;

public class GeneratorUtils {
    private static void generateConstants(String path,String classPath) throws ClassNotFoundException, MalformedURLException {
        List<String> allJavaSimpleClassNames = getAllJavaSimpleClassNames(path);
        for (String allJavaSimpleClassName : allJavaSimpleClassNames) {
            String fileName = path + allJavaSimpleClassName;
            Class<?> clazz = loadClassFromJavaFile(fileName, classPath + "." + allJavaSimpleClassName.substring(0, allJavaSimpleClassName.lastIndexOf(".java")),path);
            try {
                // Read all lines from the file
                List<String> lines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);

                // Check if constants are already generated in the file
                boolean constantsExist = lines.stream().anyMatch(line -> line.trim().equals("public interface " + allJavaSimpleClassName.substring(0, allJavaSimpleClassName.lastIndexOf(".java")) + "Fields {"));

                if (!constantsExist) {
                    // Find the last occurrence of '}' in the lines
                    int lastBraceIndex = lines.lastIndexOf("}");

                    if (lastBraceIndex != -1) {
                        // Insert constants before the last '}' in the lines
                        Field[] fields = clazz.getDeclaredFields();
                        for (Field field : fields) {
                            lines.add(lastBraceIndex, "    public static final String " + field.getName().toUpperCase() + " = \"" + field.getName() + "\";");
                        }

                        // Write the modified content back to the file
                        Files.write(Paths.get(fileName), lines, StandardCharsets.UTF_8, StandardOpenOption.TRUNCATE_EXISTING);
                        System.out.println("Constants for " + fileName + " appended to " + fileName);
                    } else {
                        System.out.println("Error: Unable to find the closing brace '}' in the file.");
                    }
                } else {
                    System.out.println("Constants for " + fileName + " already exist in " + fileName);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private static Class<?> loadClassFromJavaFile(String javaFilePath, String className, String outputDirectory) throws ClassNotFoundException, MalformedURLException {
        // 获取 Java 编译器
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

        // 编译 .java 文件，并指定输出目录
        int compilationResult = compiler.run(null, null, null, "-d", outputDirectory, javaFilePath);
        if (compilationResult != 0) {
            throw new RuntimeException("Compilation failed");
        }

        // 创建自定义类加载器，加载编译生成的 .class 文件
        URLClassLoader classLoader = new URLClassLoader(new URL[]{new File(outputDirectory).toURI().toURL()});

        // 加载类
        return Class.forName(className, true, classLoader);
    }

    public static void main(String[] args) throws ClassNotFoundException, MalformedURLException {
        //String packagePath = "D:\\自学\\nacos_config\\src\\main\\java\\com\\java\\modebing\\test\\vo";  // 替换为实际的包路径
        //
        //List<String> classNames = getAllJavaSimpleClassNames(packagePath);
        //
        //// 打印所有类名
        //for (String className : classNames) {
        //    System.out.println(className);
        //}
        generateConstants("D:\\自学\\nacos_config\\src\\main\\java\\com\\java\\modebing\\test\\vo\\","com.java.modebing.test.vo");
    }

    private static List<String> getAllJavaSimpleClassNames(String packagePath) {
        List<String> classNames = new ArrayList<>();
        File packageDirectory = new File(packagePath);

        if (packageDirectory.exists() && packageDirectory.isDirectory()) {
            // 递归获取所有的 .java 文件
            List<File> javaFiles = getAllJavaFiles(packageDirectory);

            for (File javaFile : javaFiles) {
                // 解析简单类名并添加到列表中
                String simpleClassName = javaFile.getName();
                classNames.add(simpleClassName);
            }
        }

        return classNames;
    }

    private static List<File> getAllJavaFiles(File directory) {
        List<File> javaFiles = new ArrayList<>();

        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    // 递归获取子目录中的 .java 文件
                    javaFiles.addAll(getAllJavaFiles(file));
                } else if (file.isFile() && file.getName().endsWith(".java")) {
                    javaFiles.add(file);
                }
            }
        }

        return javaFiles;
    }

}
